//index.js
const app = getApp()

Page({
  data: {
    imagePath:''
  },

  onLoad: function() {
    // 调用画布
    // this.createNewImg();
    let that=this;
    setTimeout(function(){
      that.createNewImg(); 
    },500);
  },

   /*
   1.绘制画布
   2.将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
   */
  createNewImg: function () {
    let that = this;
    let ctx = wx.createCanvasContext('myCanvas');
    //绘制文本
    //语法：fillText(text, x, y, [maxWidth]) strokeText(text, x, y, [maxWidth])
    ctx.font = "normal 18px Arial";
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';
    ctx.fillStyle = 'blue';
    ctx.fillText("我是一张图，长按可以保存", 150, 250);
    //图片绘制
    let img='../../mock/images/test.jpg';
    ctx.drawImage(img, 0, 0, 300, 200);
    ctx.save(); // 保存当前ctx的状态 ctx.restore();
    ctx.draw();
    setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 300,
        height: 320,
        destWidth: 300 * 2,//生成图片的大小设置成canvas大小的二倍解决模糊
        destHeight: 320 * 2,
        canvasId: 'myCanvas',
        fileType: 'jpg',
        success: function (res) {
          let tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath
          });
          wx.hideToast();
          console.log('canvas图片地址：' + that.data.imagePath);
        }
      });
    }, 600);
  },
   
  //点击保存到相册
  baocun: function () {
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            }
          }, fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },
})
